<?php
/**
 * BaseRepository
 * @copyright (c) 2011-2020, Hangzhou DOJI Tech Co., Ltd.
 * This is NOT a freeware, use is subject to license terms.
 * @package BaseRepository.php
 * @link https://www.tingjunapp.com/
 * @author wujun@lanqb.cn
 * @: BaseRepository.php 310000 2020-11-06 15:07:29 $
 * */

namespace App\Repository;

use App\Common\Libs\Pagination;
use App\Consts\ExceptionCode;
use App\Consts\GlobalConst;
use App\Exceptions\Error;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Validator;

class BaseRepository extends Repository
{

    /** @var null $validator */
    public $validator = null;

    /**
     * @param $targetId
     * @return int
     */
    public function getTableNumber($targetId)
    {
        return sprintf('%u', crc32($targetId)) % GlobalConst::DATABASE_TABLE_NUM;
    }

    /**
     * get pagination
     * @param array $paginationParams
     * @return Pagination
     */
    public function getPagination($paginationParams = [])
    {
        return (new Pagination())->getPagination($paginationParams);
    }

    /**
     * set pagination
     * @param Builder $provider
     * @param array|Pagination $paginationParams
     * @return Builder
     */
    public function setPagination(Builder $provider, $paginationParams = [])
    {
        if ($paginationParams instanceof  Pagination) {
            $pagination = $paginationParams;
            $pagination->page--;
        } else {
            $pagination = $this->getPagination($paginationParams);
        }

        $offset = $pagination->page * $pagination->pageSize;

        return $provider->offset($offset)->take($pagination->pageSize);
    }

    /**
     * @param array $data
     * @param array $rule
     * @param array $message
     * @return \Illuminate\Http\JsonResponse|bool
     */
    public function validate($data = [], $rule = [], $message = [])
    {
        $this->validator = Validator::make($data, $rule, $message);
        if ($this->validator->fails()) {
            return Error::handle($this->validator->errors()->first(), ExceptionCode::ILLEGAL_PARAMETER);
        }
        return true;
    }

}
